import { reactive } from 'vue'
import { type UpdatePassWordForm } from '@/api/type'
import { message } from 'ant-design-vue'
import { getSmsCode } from '@/api/user'
import { updatePassword } from '@/api/user'

interface CodeState {
  time: number
  codeDisabled: boolean
}

interface Options<T = any> {
  callback?: () => void
}

export const usePassword = (options: Options) => {
  const formState = reactive<UpdatePassWordForm>({
    phone: '',
    code: '',
    confirmPassword: '',
    password: ''
  })

  const codeState = reactive<CodeState>({
    time: 60,
    codeDisabled: false
  })

  let phoneValidate = (rule: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入手机号')
    } else if (!/^1[3456789]\d{9}$/.test(value)) {
      return Promise.reject('请输入正确的手机号')
    } else {
      return Promise.resolve()
    }
  }
  let passWordValidate = (rule: any, value: string) => {
    console.log('value',value)
    if (!value) {
      return Promise.reject('请输入密码')
    } else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+{}\[\]:;"'<>,.?/~`\\| -]{6,}$/.test(value)) {
      return Promise.reject('新密码最小长度为 6 位，且需包含数字与字母的组合')
    } else {
      return Promise.resolve()
    }
  }
  let passWordConfirmValidate = (rule: any, value: string) => {
    console.log('value',value)
    if (!value) {
      return Promise.reject('请再次输入密码')
    } else if (value !== formState.password) {
      return Promise.reject('两次密码输入不一致')
    } else {
      return Promise.resolve()
    }
  }
  const getCode = async () => {
    if (codeState.codeDisabled) {
      return
    }
    try {
      await phoneValidate({}, formState.phone)
      const { data } = await getSmsCode(formState.phone)
      if (!data.ok) return
      message.success('验证码发送成功')
      codeState.codeDisabled = true
      let timer = setInterval(() => {
        codeState.time--
        if (codeState.time <= 0) {
          clearInterval(timer)
          codeState.time = 60
          codeState.codeDisabled = false
        }
      }, 1000)
    } catch (error) {
      console.log(error)
      if (typeof error === 'string') {
        message.error(error)
      }
    }
  }
  const applyTest = async () => {
    try {
      await updatePassword(formState)
      message.success('重置密码成功')
      options?.callback?.()
    } catch (error: any) {
      console.log('error', error)
    }
  }

  return {
    formState,
    codeState,
    phoneValidate,
    passWordValidate,
    passWordConfirmValidate,
    getCode,
    applyTest
  }
}
